package cdu.bbs.bbsv2.controller;

import cdu.bbs.bbsv2.domain.Comment;
import cdu.bbs.bbsv2.domain.Topic;
import cdu.bbs.bbsv2.domain.User;
import cdu.bbs.bbsv2.service.CommentService;
import cdu.bbs.bbsv2.service.TopicService;
import cdu.bbs.bbsv2.utils.DateTimeUtil;
import cdu.bbs.bbsv2.utils.EmojiDealUtil;
import cdu.bbs.bbsv2.utils.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller()
@RequestMapping("comment")
public class CommentController {
    @Autowired
    CommentService commentService;
    @Autowired
    TopicService topicService;

    @RequestMapping("/releaseComment")
    @ResponseBody
    private Map<String, Object> releaseComment(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();

        // 得到数据封装对象
        String commentContent = request.getParameter("commentContent");
        String topicId = request.getParameter("topicId");
        String userId = ((User)session.getAttribute("user")).getId();
        String id = UUIDUtil.getUUID();
        String createTime = DateTimeUtil.getSysTime();
        Comment comment = new Comment(id, EmojiDealUtil.changeEmojiToHtml(commentContent),topicId,userId,createTime);

        // 调用service
        boolean flag = commentService.addComment(comment);

        if(flag == true) {
            // 评论次数+1
            Topic topic = topicService.getTopicById(topicId);
            topic.setCommentCount(topic.getCommentCount() + 1);
            topicService.updateInfo(topic);
        }
        // 将处理结果发回前端
        Map<String,Object> map = new HashMap<>();
        map.put("success",flag);
        return map;
    }

}
